package lyttest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import lyttest.entity.dto.FileDTO;
import lyttest.entity.dto.UserDTO;
import lyttest.service.GetInfoService;
import lyttest.uils.Response;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@Slf4j
public class GetInfoServiceImpl implements GetInfoService {

    private String managerUrl = "http://localhost:8001";

    @Resource
    RestTemplate restTemplate;

    @Override
    public ResponseEntity<String> download(UserDTO userDTO) {
        //消息头header
        HttpHeaders headers = new HttpHeaders();
        headers.set("header", "");
        // 消息体body
        FileDTO fileDTO = new FileDTO();
        fileDTO.setFileId(userDTO.getUserName());
        //消息实体
        HttpEntity<Object> requestEntity = new HttpEntity<>(fileDTO, headers);
        log.info("下载文件参数:{}", requestEntity);
        ResponseEntity<String> exchange = null;
        try {
            exchange = restTemplate
                    .exchange(managerUrl + "/file/api/downloadByUuid", HttpMethod.POST, requestEntity, String.class, new Object[0]);
            log.info("下载文件返回结果:{}", exchange.getBody());

        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public Response<String> upload(UserDTO userDTO, MultipartFile file) {
        File tmpFile = null;
        try {
            try {
                tmpFile = this.toLocalFile(file);
            } catch (IOException e) {
                log.error("导入文件失败", e);
            }
            this.uploadFile(userDTO, tmpFile);
            return Response.createSuccess("文件上传成功");
        } catch (Exception e) {
            log.error("", e);
            return Response.createError("文件上传失败.");
        }
    }

    private Response<String> uploadFile(UserDTO userDTO, File file) throws Exception {
        String rootPath = null;
        String type = "";
        //上传路径校验
        if (!rootPath.endsWith("/") || rootPath.equals("/")) {
            throw new IllegalArgumentException("上传路径必须以/结尾");
        }

        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("rootPath", "");
        headers.set("appCode", "");

        //文件
        FileSystemResource resource = new FileSystemResource(file);
        //请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", resource);
        body.add("path", "");
        // 将消息体和消息头封装到 HttpEntity 中
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(body, headers);
        ResponseEntity<String> exchange = null;
        String result = restTemplate.postForObject(managerUrl + "/file/upload/" + type, requestEntity, String.class);
        return Response.createSuccess();
    }

    public File toLocalFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //dest file
        String tmpFilePath = this.generateTmpPath(originalFilename);
        File tmpFile = new File(tmpFilePath);
        file.transferTo(tmpFile);
        return tmpFile;
    }

    public String generateTmpPath(String fileName) {
        String tempDirectoryPath = FileUtils.getTempDirectoryPath();
        // 确保 tempDirectoryPath 以路径分隔符结尾
        String tmpPath = tempDirectoryPath + (tempDirectoryPath.endsWith(File.separator) ? "" : File.separator);

        // 解析文件名和扩展名
        int index = fileName.lastIndexOf(".");
        String name = index == -1 ? fileName : fileName.substring(0, index);
        String ext = index == -1 ? "" : fileName.substring(index);

        // 构建目标文件路径（不包括最后的文件名，先构建目录路径）
        File dirPath = new File(tmpPath);
        // 确保目录存在
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        // 现在构建完整的文件路径
        StringBuilder targetPath = new StringBuilder(tmpPath);
        targetPath.append(name).append(ext);

        return targetPath.toString();
    }
}